/*

	2021-08-12
	封装uni-app请求
	
*/
import config from "./config.js";

function request(params, method) {
	let token = uni.getStorageSync("token") || '';
	let tenantId = uni.getStorageSync("tenantId") || '';
	// console.log(token, tenantId)
	return new Promise(function(resolve, reject) {
		// console.log('base_url-------',config.base_url);
		// 根据具体业务需求更改必要参数
		if (!config.base_url || !config._acid || !config._uniacid) {
			console.log('config.js 中参数配置不全');
			reject('config.js 中参数配置不全');
			return
		}

		// console.log('前台传的数据:', params)
		uni.request({
			url: config.base_url + params.url,
			data: params.data,
			method: method,
			header: {
				"Authorization": config.authBasic,
				"Blade-Auth": token,
				"tenant-id": tenantId,
				...params.header
			},
			timeout: config.reqTimeOut,
			success(res) {
				// 成功回调
				if (res.statusCode == 200) {
					// console.log('后台返回的数据',res);
					if (res.data.data != null && res.data.data.hasOwnProperty('token')) {
						// console.log('后台返回了token token已保存-----')
						try {
							uni.setStorageSync('token', res.data.data.token);
						} catch (e) {}
					} else if (res.data.code == 401 || res.data.code == 502) {
						try {
							uni.setStorageSync('isUserTrue', 'false');
						} catch (e) {}
						uni.reLaunch({
							url: '/pageLogin/login'
						});
					}
					resolve(res.data)
				} else {
					if (res.statusCode == 401) {
						try {
							uni.setStorageSync('isUserTrue', 'false');
						} catch (e) {}
						uni.reLaunch({
							url: '/pageLogin/login'
						});

					} else {
						resolve(res.data)
					}
				}
			},
			fail(e) {
				console.log('客户端请求超时-----', e)
				uni.showToast({
					title: '客户端请求超时',
					icon: "none"
				})

				let params = {
					code: config.clientStatus.status5504,
					success: false
				}
				resolve(params)
			},
			complete() {
				// 无论成功或失败 只要请求完成的 回调
				// console.log('ajax------complete');
			}
		})
	})
};



export default {
	async get(params) {
		return request(params, "GET");
	},
	async post(params) {
		return await request(params, "POST")
	}
}
